<script setup>
import { useUserStore } from '@/stores/user';
import JWeixin from 'weixin-js-sdk';
import { Toast, Dialog } from 'vant';
import { queryUrlParam } from '@/utils/tools';
import { EiInfo } from '@eplat/ei';
// 调用4j的service
import api4j from '@/api/example';

const router = useRouter();
const user = useUserStore();
const loading = ref(false);
const loadings = ref(false);
const loadingss = ref(false);
const finish = ref(false);
const page = reactive({
  pageSize: 10,
  currentPage: 0,
  result: []
});
// // 授权
// JWeixin.config({
//   debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//   appId: api4j.APPID, // 必填，公众号的唯一标识
//   timestamp: '', // 必填，生成签名的时间戳
//   nonceStr: '', // 必填，生成签名的随机串
//   signature: '', // 必填，签名
//   jsApiList: [] // 必填，需要使用的JS接口列表
// });
// JWeixin.ready(async () => {
//   // 获取用户code
//   const code = queryUrlParam('code');
//   // 没有授权code
//   if (code == null) {
//     // Toast('授权失败');
//     // 跳转到授权页面
//     window.location.href =
//       'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
//       api4j.APPID +
//       '&redirect_uri=https%3A%2F%2F' +
//       api4j.SERVER_DOMAIN +
//       '%2F%23%2FWX%2FWD%2FWXWD09&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
//   } else {
//     // 本地没有token新授权
//     if (user.getToken == '' || user.getToken == undefined) {
//       // Toast('正在授权');
//       const postEiInfo = new EiInfo();
//       postEiInfo.set('code', code);
//       // 通过code获取用户信息
//       await api4j.wxLogin(postEiInfo).then((res) => {
//         // 如果授权无效 重新授权
//         if (res.status !== 1) {
//           // Toast(res.msg);
//           window.location.href =
//             'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
//             api4j.APPID +
//             '&redirect_uri=https%3A%2F%2F' +
//             api4j.SERVER_DOMAIN +
//             '%2F%23%2FWX%2FWD%2FWXWD09&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
//           return;
//         }
//         // Toast(res.msg);
//         // token info存放本地
//         user.setUserInfo(
//           res.extAttr.token,
//           res.extAttr.userInfo.attrs.headimgurl,
//           res.extAttr.userInfo.attrs.nickname
//         );
//         user.setUserNameTel(res.extAttr.username, res.extAttr.phone);
//
//         onLoad();
//       });
//     }
//   }
// });

// 授权
JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID1, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        api4j.APPID1 +
        '&redirect_uri=https%3A%2F%2F' +
        api4j.SERVER_DOMAIN1 +
        '%2F%23%2FWX%2FWD%2FWXWD12&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    if (user.getToken == '' || user.getToken == undefined) {
      // Toast('正在授权');
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogins(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          // Toast(res.msg)
          window.location.href =
              'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
              api4j.APPID1 +
              '&redirect_uri=https%3A%2F%2F' +
              api4j.SERVER_DOMAIN1 +
              '%2F%23%2FWX%2FWD%2FWXWD12&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        // Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
            res.extAttr.token,
            res.extAttr.userInfo.attrs.headimgurl,
            res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);

        onLoad();
      });
    }
  }
});


const onLoad = async () => {
  loading.value = true;
  applyList();
  loading.value = false;
};

const applyList = async () => {
  loadingss.value = true;
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken);
  await api4j
    .RCRM0103_bindZJZCQuery(postEiInfo)
    .then((res) => {
      page.result = [];
      // console.log('12qwe', res.extAttr.datas);
      const data = res.extAttr.datas;
      if (data.length === 0) {
        page.result = [];
      } else {
        page.result.push(...data);
      }
      loadingss.value = false;
    })
    .catch((error) => {
      if (error.response && error.response.status === 429) {
        // eslint-disable-next-line no-undef
        Toast('请勿频繁操作');
      }
    });
};
const deleteZCInfo = async (item) => {
  Dialog.confirm({
    title: '删除',
    message: '确认进行删除吗?'
  })
    .then(async () => {
      const postEiInfo = new EiInfo();
      postEiInfo.set('token', user.getToken);
      postEiInfo.set('reserve1', item.reserve1);
      postEiInfo.set('reserve2', item.reserve2);
      postEiInfo.set('reserve3', item.reserve3);
      postEiInfo.set('reserve4', item.reserve4);
      postEiInfo.set('zjZcId', item.zjZcId);
      await api4j
        .RCRM0103_bindZJZCDelete(postEiInfo)
        .then((res) => {
          Toast(res.msg);
          zcClear();
          onLoad();
          shows.value = false;
        })
        .catch((error) => {
          if (error.response && error.response.status === 429) {
            // eslint-disable-next-line no-undef
            Toast('请勿频繁操作');
          }
        });
    })
    .catch(() => {
      // on cancel
    });
};
const clearData = async () => {};
const clearDatas = async () => {};
const shows = ref(false);
const showss = ref(false);
const ids = ref('');
const val8 = ref([]);
const showData = async () => {
  Toast('确认');
  val8.value = checked.value;
};
const cancelData = async () => {
  Toast('取消');
  val8.value = [];
  checked.value = [];
};

const checked = ref([]);
const dataList = ref([]);
const YHName = ref('');
const YHPhone = ref('');

const zcClear = async () => {
  YHName.value = '';
  YHPhone.value = '';
  val8.value = [];
  checked.value = [];
  const divTab = document.getElementById('divTab');
  divTab.style.display = 'none';
};
const ycClear = async () => {
  WYYC.value = '';
  DFYC.value = '';
  SFYC.value = '';
  KTYC.value = '';
};
const yucun = async (item) => {
  showss.value = true;
  ids.value = item.zcId + '-' + item.reserve1;
};
const WYYC = ref('');
const DFYC = ref('');
const SFYC = ref('');
const KTYC = ref('');

// 缴费操作
const getOrder = async (res) => {
  if (
    res.extAttr.order == '' ||
    res.extAttr.money == '' ||
    res.extAttr.body == '' ||
    res.extAttr.remark == ''
  ) {
    Toast.fail('支付明细信息失败');
    return;
  }
  const eiInfo = new EiInfo();
  eiInfo.set('orgid', 'JXZY00'); // 企业：XSF00=重庆新沙纺房屋租赁有限公司,JXZY00=江厦置业,JXXH00=江厦徐汇,YDWY00=渝地物业江厦星光汇
  eiInfo.set('reqsn', res.extAttr.order); // 订单编号
  eiInfo.set('trxamt', res.extAttr.money); // 金额：分
  eiInfo.set('returl', 'http://' + api4j.SERVER_DOMAIN + '/#/WX/wd/WXwd08');
  eiInfo.set('body', res.extAttr.body);
  eiInfo.set('remark', res.extAttr.remark);
  // 支付成功的信息
  eiInfo.set('orders', res.extAttr.orders);
  eiInfo.set('uuids', res.extAttr.uuids);
  eiInfo.set('moneys', res.extAttr.moneys);
  eiInfo.set('usernames', res.extAttr.usernames);
  eiInfo.set('accounts', res.extAttr.accounts);
  eiInfo.set('orgIds', res.extAttr.orgIds);

  await api4j.RCRM0103_goJf(eiInfo).then((e) => {
    // console.log('reseeeee', e);
    if (e.status == 0) {
      const result = e.getBlock('result');
      let key = '';
      key = 'appid';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'cusid';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'charset';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'trxamt';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'reqsn';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'returl';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'notify_url';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'body';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'randomstr';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'remark';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'validtime';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'signtype';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'version';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      // key = 'paytype';
      // document.getElementById(key).value = result.getCell(0, key);
      // //console.log(result.getCell(0, key));
      key = 'sign';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));

      const gatewayForm = document.getElementById('gatewayForm');
      gatewayForm.submit();
    }
  });
};

const onSubmits = async () => {
  if (WYYC.value == '' && DFYC.value == '' && SFYC.value == '' && KTYC.value == '') {
    Toast('请至少输入一条费用金额');
    return;
  }
  // console.log(ids.value);
  Dialog.confirm({
    title: '预存充值',
    message: '确认进行预存充值吗?'
  })
    .then(async () => {
      const postEiInfo = new EiInfo();
      postEiInfo.set('WYYC', WYYC.value);
      postEiInfo.set('DFYC', DFYC.value);
      postEiInfo.set('SFYC', SFYC.value);
      postEiInfo.set('KTYC', KTYC.value);
      postEiInfo.set('token', user.getToken);
      postEiInfo.set('username', user.getUsername);
      postEiInfo.set('ids', ids.value);
      await api4j
        .RCRM0103_ycfy(postEiInfo)
        .then((res) => {
          // console.log('wwww', res);
          if (res.status == 1) {
            getOrder(res);
            onLoad();
            return;
          }
          Toast('未查询到明细');
        })
        .catch((error) => {
          if (error.response && error.response.status === 429) {
            // eslint-disable-next-line no-undef
            Toast('请勿频繁操作');
          }
        });
    })
    .catch(() => {
      // on cancel
    });
};
// 模糊查询客户
const onSubmit = async () => {
  loadings.value = true;
  const postEiInfo = new EiInfo();
  postEiInfo.set('name', YHName.value);
  // postEiInfo.set('phone', YHPhone.value);
  await api4j
    .RCRM0103_zcZJCodeQuery(postEiInfo)
    .then((res) => {
      Toast(res.msg);
      if (res.status == 1) {
        console.log('123', res);
        dataList.value = res.extAttr.dataList;
        // dataList.value = res.extAttr.dataList.map((item) => {
        //   return {
        //     ...item,
        //     reserve5: JSON.parse(item.reserve5)
        //   };
        // });
        // console.log('456',dataList.value)
        const divTab = document.getElementById('divTab');
        divTab.style.display = 'block';
        loadings.value = false;
        return;
      }
      const divTab = document.getElementById('divTab');
      divTab.style.display = 'none';
      loadings.value = false;
    })
    .catch((error) => {
      if (error.response && error.response.status === 429) {
        // eslint-disable-next-line no-undef
        Toast('请勿频繁操作');
      }
    });
};
// 绑定租金资产
const onSubmit1 = async () => {
  Dialog.confirm({
    title: '绑定',
    message: '确认进行绑定吗?'
  })
    .then(async () => {
      const postEiInfo = new EiInfo();
      postEiInfo.set('token', user.getToken);
      postEiInfo.set('userName', user.getUsername);
      postEiInfo.set('zcData', val8.value);

      await api4j
        .RCRM0103_bindZJZC(postEiInfo)
        .then((res) => {
          Toast(res.msg);
          zcClear();
          onLoad();
          shows.value = false;
        })
        .catch((error) => {
          if (error.response && error.response.status === 429) {
            // eslint-disable-next-line no-undef
            Toast('请勿频繁操作');
          }
        });
    })
    .catch(() => {
      // on cancel
    });
};
// 全选 反选
const checkAll = () => {
  checkboxGroup.value.toggleAll(true);
};
const toggleAll = () => {
  checkboxGroup.value.toggleAll();
};
const checkboxGroup = ref(null);
</script>
<template>
  <van-list
    v-model:loading="loading"
    class="working-list"
    :finished="finish"
    finished-text=""
    offset="1"
    @load="onLoad"
  >
    <div
      style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #4b75e5;
        height: 65px;
        color: white;
        z-index: 1000;
      "
    >
      <div style="font-size: 20px; padding-top: 20px; text-align: center">租金资产</div>
      <van-button
        to="/WX/WD/WXWD12"
        style="
          background-color: #4b75e5;
          color: white;
          display: flex;
          flex-direction: column;
          align-items: center;
          border: 1px solid #4b75e5;
          margin-top: -32px;
          margin-left: 20px;
        "
      >
        <img
          src="@/assets/tb166.svg"
          style="width: 35px; height: 35px; margin-left: -20px; margin-top: 3px"
          alt=""
        />
      </van-button>
    </div>
    <div>
      <van-loading v-if="loadingss" type="spinner" style="margin-top: 75px; text-align: center" />
    </div>
    <div style="margin-top: 75px">
      <van-cell-group
        v-for="(item, index) in page.result"
        :key="index"
        style="margin-left: 20px; margin-right: 20px"
        inset
      >
        <van-cell style="width: 100%">
          <div style="display: flex">
            <div>
              <img
                src="@/assets/tb144.svg"
                style="width: 32px; height: 32px; margin-top: 30px"
                alt=""
              />
            </div>
            <div style="margin-left: 20px">
              <div style="font-size: 15px; font-weight: bold; margin-top: 10px">
                {{ item.reserve1 }}
              </div>
              <div style="margin-top: 5px">
                时段:
                <span style="color: red; font-size: 15px"
                  >{{ item.reserve3 }} <span style="color: black">至</span>
                  {{ item.reserve4 }}</span
                >
              </div>
              <div style="margin-top: 5px; width: 240px">客户：{{ item.reserve2 }}</div>
              <!--              <div style="margin-top: 5px">客户电话：02368806700</div>-->
              <!--              <div style="margin-top: 5px">重庆江厦置业有限责任公司</div>-->
            </div>

            <van-button
              round
              style="
                width: 30px;
                font-weight: bold;
                color: white;
                display: flex;
                flex-direction: column;
                align-items: center;
                border: 1px solid white;
                margin-top: 27px;
                margin-left: 5px;
              "
              @click="deleteZCInfo(item)"
            >
              <img src="@/assets/tb309.svg" alt="" style="width: 30px; height: 30px" />
            </van-button>
          </div>
        </van-cell>
      </van-cell-group>
      <van-button
        type="primary"
        style="width: 90%; margin-left: 20px; margin-right: 20px; background-color: #4b75e5"
        @click="shows = true"
        ><span>+&nbsp;绑定资产</span>
      </van-button>
      <van-popup
        v-model:show="showss"
        v-model="ids"
        class="form-cell-group"
        closeable
        close-icon="close"
        position="bottom"
        close-icon-position="top-right"
        close-icon-size="100px"
        :style="{ width: '100%', height: '90%' }"
        :close="clearDatas()"
      >
        <div style="margin-top: 50px; margin-left: 16px; display: flex">
          <span style="color: red; margin-top: 9px; margin-right: 2px">*</span>
          <span style="margin-top: 6px">费用信息</span>
          <van-button
            type="default"
            icon="delete-o"
            size="small"
            style="margin-left: 170px; background-color: #4b75e5; color: white"
            plain
            @click="ycClear"
            >清除记录</van-button
          >
        </div>
        <van-form @submit="onSubmits">
          <van-field
            v-model="WYYC"
            type="number"
            label="物业预存费:"
            placeholder="请输入物业预存费"
            center
            style="margin-top: 15px"
          ></van-field>

          <van-field
            v-model="DFYC"
            label="电费预存费:"
            placeholder="请输入电费预存费"
            center
            style="margin-top: 15px"
            type="number"
          ></van-field>

          <van-field
            v-model="SFYC"
            label="水费预存费:"
            placeholder="请输入水费预存费"
            center
            style="margin-top: 15px"
            type="number"
          ></van-field>

          <van-field
            v-model="KTYC"
            label="空调预存费:"
            placeholder="请输入空调预存费"
            center
            style="margin-top: 15px"
            type="number"
          ></van-field>

          <van-button
            style="margin-top: 10px; background-color: #4b75e5"
            type="primary"
            block
            native-type="submit"
            >充值</van-button
          >
        </van-form>
      </van-popup>
      <van-popup
        v-model:show="shows"
        class="form-cell-group"
        closeable
        close-icon="close"
        position="bottom"
        close-icon-position="top-right"
        close-icon-size="100px"
        :style="{ width: '100%', height: '90%' }"
        :close="clearData()"
      >
        <div style="margin-top: 50px; margin-left: 16px; display: flex">
          <span style="color: red; margin-top: 9px; margin-right: 2px">*</span>
          <span style="margin-top: 6px">绑定信息</span>
          <van-button
            type="default"
            icon="delete-o"
            size="small"
            style="margin-left: 170px; background-color: #4b75e5; color: white"
            plain
            @click="zcClear"
            >清除记录</van-button
          >
        </div>
        <van-form @submit="onSubmit">
          <van-field
            v-model="YHName"
            required
            label="客户名称："
            placeholder="请输入客户名称（模糊匹配）"
            center
            style="margin-top: 15px"
            :rules="[{ required: true, message: '请输入客户名称' }]"
          ></van-field>

          <!--          <van-field-->
          <!--            v-model="YHPhone"-->
          <!--            required-->
          <!--            label="手机号码："-->
          <!--            placeholder="请输入手机号码"-->
          <!--            center-->
          <!--            style="margin-top: 15px"-->
          <!--            type="tel"-->
          <!--            :rules="[{ required: true, message: '请输入手机号码' }]"-->
          <!--          ></van-field>-->
          <van-button
            style="margin-top: 10px; background-color: #4b75e5"
            type="primary"
            block
            native-type="submit"
            >查询</van-button
          >
          <van-loading v-if="loadings" style="text-align: center" />
        </van-form>

        <div id="divTab" style="display: none; margin-top: 10px">
          <van-form @submit="onSubmit1">
            <van-field
              v-model="val8"
              class="titles"
              label="资产信息:"
              placeholder="请选择资产信息"
              required
              center
              type="textarea"
              readonly
              rows="3"
              :rules="[{ required: true, message: '资产信息不能为空' }]"
            >
            </van-field>
            <van-dropdown-menu active-color="#ee0a24" style="margin-top: 10px">
              <van-dropdown-item id="dropdownItem" title="选择资产信息" style="width: 100%">
                <van-checkbox-group
                  ref="checkboxGroup"
                  v-model="checked"
                  direction="horizontal"
                  style=""
                >
                  <van-button type="primary" style="margin-left: 25%" @click="checkAll"
                    >全选</van-button
                  >
                  <van-button type="primary" style="margin-left: 20%" @click="toggleAll"
                    >反选</van-button
                  >
                  <van-cell v-for="(item, index) in dataList" :key="index">
                    <van-checkbox
                      v-model="item.reserve5"
                      :name="
                        item.contractName +
                        '/' +
                        item.customerName +
                        '/' +
                        item.startDate +
                        '/' +
                        item.endDate +
                        '/' +
                        item.ledgerLineNos
                      "
                      shape="square"
                      >{{ item.contractName }}({{ item.customerName }}-
                      <span style="color: red">{{ item.startDate }}</span>
                      -<span style="color: red">{{ item.endDate }}</span
                      >)</van-checkbox
                    >
                  </van-cell>
                </van-checkbox-group>
                <van-button
                  style="margin-left: 200px; background-color: #4b75e5; color: white"
                  @click="cancelData()"
                  >取 消</van-button
                >
                <van-button
                  style="margin-left: 30px; background-color: #4b75e5; color: white"
                  @click="showData()"
                  >确 认</van-button
                >
              </van-dropdown-item>
            </van-dropdown-menu>

            <van-button
              style="margin-top: 10px; background-color: #4b75e5"
              type="primary"
              block
              native-type="submit"
              >绑定</van-button
            >
          </van-form>
        </div>
      </van-popup>
    </div>
    <div style="display: none">
      <form
        id="gatewayForm"
        name="gatewayForm"
        action="https://syb.allinpay.com/apiweb/h5unionpay/unionorder"
        method="POST"
      >
        <input id="appid" type="hidden" name="appid" />
        <input id="cusid" type="hidden" name="cusid" />
        <input id="version" type="hidden" name="version" />
        <input id="charset" type="hidden" name="charset" />
        <input id="trxamt" type="hidden" name="trxamt" />
        <input id="reqsn" type="hidden" name="reqsn" />
        <input id="randomstr" type="hidden" name="randomstr" />
        <input id="body" type="hidden" name="body" />
        <input id="validtime" type="hidden" name="validtime" />
        <input id="remark" type="hidden" name="remark" />
        <input id="returl" type="hidden" name="returl" />
        <input id="notify_url" type="hidden" name="notify_url" />
        <input id="signtype" type="hidden" name="signtype" />
        <input id="sign" type="hidden" name="sign" />
      </form>
    </div>
  </van-list>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
